#include "StdAfx.h"
#include "UCLabel.h"


CUCLabel::CUCLabel(void)
{
}

CUCLabel::~CUCLabel(void)
{
}

void CUCLabel::SetPos(RECT rc)
{
	CRichEditUI::SetPos(rc);
	CDuiString strText = CaculateText();
	__super::SetText(strText);
}

HRESULT CUCLabel::TxSendMessage(UINT msg, WPARAM wparam, LPARAM lparam, LRESULT *plresult) const
{
	if( m_pTwh ) {
		if( (msg==WM_KEYDOWN || msg==WM_KEYUP) && TCHAR(wparam) == VK_RETURN ) {
			if( m_bWantReturn || (::GetKeyState(VK_CONTROL) < 0 && m_bWantCtrlReturn) ) {
				if( m_pManager != NULL ) m_pManager->SendNotify((CControlUI*)this, DUI_MSGTYPE_RETURN, msg);
				return S_OK;
			}
		}
		int res = __super::TxSendMessage(msg, wparam, lparam, plresult);
		if (msg == WM_LBUTTONDOWN)
		{
			::HideCaret(m_pManager->GetPaintWindow());
		}
		
		return res;
	}
	return S_FALSE;
}

void CUCLabel::DoEvent(TEventUI& event)
{
	if( event.Type == UIEVENT_SETFOCUS ) 
	{
		__super::SetText(m_strAllText);
		SetSel(0,0);
	}
	if( event.Type == UIEVENT_KILLFOCUS )  
	{
		CDuiString strText = CaculateText();
		__super::SetText(strText);
		SetSel(0,0);
	}

	__super::DoEvent(event);
}


CDuiString CUCLabel::CaculateText()
{
	if (m_pManager == NULL || ::IsRectEmpty(&m_rcItem))
	{
		return m_strAllText;
	}

	HWND hwnd = m_pManager->GetPaintWindow();
	if (hwnd == NULL || !IsWindow(hwnd))
	{
		return m_strAllText;
	}

	CDuiString strText = m_strAllText;

	HDC hdc = GetDC(hwnd);

	int width = 0;

	HFONT hFont = m_pManager->GetFont(m_iFont);
	HFONT hOldFonat = (HFONT)::SelectObject(hdc,hFont);

	CDuiRect rc(0,0,1024,1024);
	int len = strText.GetLength();
	
	while (len > 0)
	{
		DrawText(hdc,strText.GetData(),len,&rc,DT_LEFT|DT_SINGLELINE|DT_CALCRECT);
		if (rc.GetWidth() <= m_rcItem.right - m_rcItem.left)
		{
			if (len != strText.GetLength())
			{
				int k = len - 3;
				if (k > -1)
				{
					strText = m_strAllText.Left(k) + _T("...");
				}
			}
			break;
		}

		--len;
	}

	::SelectObject(hdc,hOldFonat);
	ReleaseDC(hwnd,hdc);

	return strText;
}

void CUCLabel::SetText(LPCTSTR pstrText)
{
	if (m_pManager == NULL)
	{
		return;
	}

	m_strAllText = pstrText;

	CDuiString strText = CaculateText();
	
	__super::SetText(strText);
}
